import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/db/isar.dart';

import '../../../util/utils.dart';

class WorkNoteController extends BaseController with LocalDataWorkNoteInfo {
  final date = ''.obs;
  final noteList = <WorkNoteInfo>[].obs;

  TextEditingController _textEditingController = TextEditingController();

  TextEditingController get textEditingController => _textEditingController;

  onInit() async {
    super.onInit();
    await queryWorkNoteInfo();
    noteList.assignAll(notes);
  }

  addRecord() {
    selectTime();
  }

  selectTime() async {
    var dateTime = await showDatePicker(
      context: Get.overlayContext!,
      initialDate: DateTime.now(),
      firstDate: DateTime(1970),
      lastDate: DateTime.now(),
    );
    if (dateTime != null) {
      print('datetime:$dateTime');
      WorkNoteInfo note = WorkNoteInfo();
      date.value = formatDate(dateTime);
      if (await notes.isExist(date.value)) {
        toast('当前日期已存在,请重新选择');
        return;
      }
    }
  }

  save() async {
    WorkNoteInfo note = WorkNoteInfo();
    note.id = DateTime.now().millisecondsSinceEpoch;
    note.date = date.value;
    note.content = _textEditingController.text;
    print('date:${note.date}');
    notes.save(note);
    noteList.add(note);
    noteList.sort((a, b) => b.date.compareTo(a.date)); //从小到大
    _textEditingController.clear();
    date.value = '';
  }

  deleteRecord(String date) {
    toast('删除');
    notes.delete(date);
    noteList.removeWhere((it) => it.date == date);
    noteList.refresh();
  }

  copyContent(String content) {
    copyToClipboard(content);
    toast('复制成功');
  }
}
